<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/17
 * Time: 17:01
 */
class Db{
    public $table;//操作数据的表
    public $error;
    public $opt = [
        'where' => '',
        'order' => '',
        'limit' => '',
        'group' => '',
        'having' => '',
    ];

    //插入数据
    public function insert($data){
        $fields = array_keys($data);
        $values = array_values($data);
        $values = "'".implode("','",$values)."'";

        $sql = 'INSERT INTO '.$this->table.' ('.implode(',',$fields).') VALUES ('.$values.')';

        return $this->exe($sql);
    }

    //条件
    public function where($where){
        if(!is_null($where)){
            $this->opt['where'] = ' WHERE '.$where;
        }
    }

    //限制条数
    public function limit($limit){
        $this->opt['limit'] = ' LIMIT '.$limit;
    }

    //查询
    public function select(){
        $sql = "SELECT * FROM ".$this->table.$this->opt['where'].$this->opt['group'].$this->opt['having'].$this->opt['order'].$this->opt['limit'];
        return $this->query($sql);
    }

    //更新
    public function update($data){
        //update table set xx=xx,xx=xx where
        $where = $this->opt['where'];
        if(is_null($where) || empty($where)){
            halt('更新时条件不能为空');
        }
        $sql = 'UPDATE '.$this->table.' SET ';
        foreach($data as $field => $value){
            $sql .= $field.'="'.$value.'",';
        }
        $sql = trim($sql,',');
        return $this->exe($sql);
    }

    //删除
    public function delete(){
        //delete from table where id=1;
        $where = $this->opt['where'];
        if(is_null($where) || empty($where)){
            halt('删除时条件不能为空');
        }

        $sql = 'DELETE FROM '.$this->table.$this->opt['where'];
        return $this->exe($sql);
    }
}